package com.jinbiao.quasar.websocket;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.jinbiao.quasar.constant.RedisBucketKey;
import com.jinbiao.quasar.model.SysUser;
import com.jinbiao.quasar.util.RedisUtil;
import org.noear.solon.annotation.ServerEndpoint;
import org.noear.solon.core.message.Listener;
import org.noear.solon.core.message.Message;
import org.noear.solon.core.message.Session;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(path = "/public/ws/{username}")
public class NoticeAndMsgListener  implements Listener {
    public static final HashMap<String,Session> sessionMap = new HashMap<>();
    @Override
    public void onOpen(Session session) {
        System.out.println("用户名:"+session.param("username")+"---webSocket连接成功");
        sessionMap.remove(session.param("username"));
        sessionMap.put(session.param("username"),session);
        Listener.super.onOpen(session);
    }

    @Override
    public void onMessage(Session session, Message message) throws IOException {
        String username = session.param("username");
        System.out.println("接收到"+username+"发来消息："+message.bodyAsString());
    }

    @Override
    public void onClose(Session session) {
        Listener.super.onClose(session);
    }

    @Override
    public void onError(Session session, Throwable error) {
        Listener.super.onError(session, error);
    }

    public static void sendMsg(String username,String msg){
        if(sessionMap.get(username)!=null) {
            sessionMap.get(username).send(msg);
        }
    }
    public static void sendMsg(List<String> usernames, String msg){
        for(String username: usernames) {
            if(sessionMap.get(username)!=null) {
                sessionMap.get(username).send(msg);
            }
        }
    }
}
